package com.cloudspace.jindun.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.android.volley.error.VolleyError;
import com.cloudspace.jindun.R;
import com.cloudspace.jindun.activity.dianhua.ContactActivity;
import com.cloudspace.jindun.activity.dianhua.EmergencyActivity;
import com.cloudspace.jindun.activity.dianhua.HistoryActivity;
import com.cloudspace.jindun.adapter.ContactAdatper;
import com.cloudspace.jindun.adapter.PersonContactAdatper;
import com.cloudspace.jindun.config.Configs;
import com.cloudspace.jindun.log.APPLog;
import com.cloudspace.jindun.manager.ContactPersonManager;
import com.cloudspace.jindun.model.ContactPersonListResult;
import com.cloudspace.jindun.model.Person;
import com.cloudspace.jindun.network.api.API;
import com.cloudspace.jindun.network.base.ApiCallback;
import com.cloudspace.jindun.ui.WordsNavigation;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.CallingUtils;
import com.cloudspace.jindun.utils.ObjUtil;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import static java.net.HttpURLConnection.HTTP_OK;

/**
 * Created by zengxianhua on 16/12/19.
 */

public class DialFragment extends BaseFragment implements View.OnClickListener,TextWatcher {
    private static final String ARG_SECTION_NUMBER = "section_number";

    private ListView searchResultListView;
    private PersonContactAdatper dialAdatper;
    private View rootView;
    private EditText phoneNumberEdit;

    private EditText contactEdit;
    private Button delteView;

    private View contactView;
    private View dialView;

    private List<Person> contactPersons;

    private ContactAdatper contactAdatper;
    private ListView contactPersonList;
    private WordsNavigation mWordsNavigation;

    //紧急联系人
    private View emerLy;

    //隐藏软键盘
    private void hideSoftKeyboard() {
        if (phoneNumberEdit == null) {
            return;
        }

        if (android.os.Build.VERSION.SDK_INT <= 10) {
            phoneNumberEdit.setInputType(InputType.TYPE_NULL);
        } else {
            getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setSoftInputShownOnFocus;
                setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setSoftInputShownOnFocus.setAccessible(true);
                setSoftInputShownOnFocus.invoke(phoneNumberEdit, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private List<Person> toDialPersons = new ArrayList<Person>();

    public void initDialDatas() {
        toDialPersons = ContactPersonManager.getInstance().queryAll();
        dialAdatper.setData(toDialPersons);
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_dianhua, container, false);
        initView();
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    public static final String TAG = DialFragment.class.getSimpleName();

    private List<Person> personsFromNetwork = new ArrayList<Person>();

    private void getDataFromNetwork(String userId){
        if (TextUtils.isEmpty(userId)){
            APPLog.zxhLog("getDataFromNetwork error");
            return;
        }


        API.getInstance().getOrgApi().getContactPersons(TAG, userId, new ApiCallback<ContactPersonListResult>() {
            @Override
            public void handleResult(ContactPersonListResult result, VolleyError error) {
                if (result != null && result.status == HTTP_OK) {
                    ContactPersonManager.getInstance().deleteAll();

                    if (!ObjUtil.isEmpty(result.data)){
                        personsFromNetwork = result.data;
                        for (Person person : personsFromNetwork) {
                            transferToLocalTestSipAccount(person);
                            ContactPersonManager.getInstance().addContactPerson(Person.contructContactPerson(person));
                        }
                    }
                }

                initContactData();
                initDialDatas();

            }
        });
    }

    private void transferToLocalTestSipAccount(Person person) {
        if (!ObjUtil.isEmpty(person) && !ObjUtil.isEmpty(person.getSipAccount())){
            String userName = person.getSipAccount().split("@")[0];
            person.setSipAccount(userName+ "@" + Configs.SIP_DOMAIN);
        }
    }

    private void loadData() {
        getDataFromNetwork(UserSessionManager.getInstance().getUserId());
    }

    private void initView() {
        dialView = rootView.findViewById(R.id.call_dial);
        dialView.setVisibility(View.GONE);
        contactView = rootView.findViewById(R.id.call_contact);

        emerLy = rootView.findViewById(R.id.emerLy);
        emerLy.setOnClickListener(this);

        searchResultListView = (ListView) dialView.findViewById(R.id.serachResultList);
        phoneNumberEdit = (EditText) dialView.findViewById(R.id.phone_edittext_call);
        phoneNumberEdit.addTextChangedListener(this);

        contactEdit = (EditText) contactView.findViewById(R.id.phone_edit_search);
        mWordsNavigation= (WordsNavigation) contactView.findViewById(R.id.MyWordsNavigation);
        contactEdit.addTextChangedListener(this);

        dialAdatper = new PersonContactAdatper();
        searchResultListView.setAdapter(dialAdatper);
        setListener();
        hideSoftKeyboard();

        contactPersonList = (ListView) contactView.findViewById(R.id.phone_list_contracts);
        contactAdatper = new ContactAdatper(getActivity());
        contactPersonList.setAdapter(contactAdatper);

        contactPersonList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Person person = contactPersons.get(position);
                if (person != null){
                    CallingUtils.showCallMethodDialog(getActivity(), person);
                }
            }
        });
    }

    private void initContactData() {
        contactPersons = ContactPersonManager.getInstance().queryAll();
        contactAdatper.setDatas(contactPersons);
    }

    private void setListener() {
        rootView.findViewById(R.id.Btn1).setOnClickListener(this);
        rootView.findViewById(R.id.Btn2).setOnClickListener(this);
        rootView.findViewById(R.id.Btn3).setOnClickListener(this);
        rootView.findViewById(R.id.Btn4).setOnClickListener(this);
        rootView.findViewById(R.id.Btn5).setOnClickListener(this);
        rootView.findViewById(R.id.Btn6).setOnClickListener(this);
        rootView.findViewById(R.id.Btn7).setOnClickListener(this);
        rootView.findViewById(R.id.Btn8).setOnClickListener(this);
        rootView.findViewById(R.id.Btn9).setOnClickListener(this);
        rootView.findViewById(R.id.Btn0).setOnClickListener(this);
        rootView.findViewById(R.id.BtnXing).setOnClickListener(this);
        rootView.findViewById(R.id.BtnJing).setOnClickListener(this);

        rootView.findViewById(R.id.contact_dial).setOnClickListener(this);
        rootView.findViewById(R.id.contact_lianxi).setOnClickListener(this);
        rootView.findViewById(R.id.contact_history).setOnClickListener(this);

        contactView.findViewById(R.id.dianhua_iv_contactActivity).setOnClickListener(this);

        searchResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Person person = toDialPersons.get(position);
                CallingUtils.showCallMethodDialog(getActivity(), person);
            }
        });
        delteView = (Button) rootView.findViewById(R.id.delete);
        delteView.setOnClickListener(this);
        delteView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                phoneNumberEdit.setText("");
                return false;
            }
        });

        contactEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    contactEdit.setCompoundDrawables(null, null, null, null);
                }
            }
        });
        //设置右侧触摸监听
        mWordsNavigation.setOnTouchingLetterChangedListener(new WordsNavigation.OnTouchingLetterChangedListener() {

            @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = contactAdatper.getPositionForSection(s.charAt(0));
                if(position != -1 && position < contactAdatper.getCount()){
                    View item = contactAdatper.getView(position, null, contactPersonList);
                    item.measure(0, 0);
                    contactPersonList.setSelectionFromTop(position, item.getMeasuredHeight());

                }
                Log.e("LOG",position+"");
            }
        });
    }

    @Override
    public void onFragmentCreated(Bundle savedInstanceState) {

    }

    @Override
    public void updateContent() {

    }

    public static DialFragment newInstance(int sectionNumber) {
        DialFragment fragment = new DialFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.Btn1) {
            keyPressed(KeyEvent.KEYCODE_1);
        } else if (v.getId() == R.id.Btn2) {
            keyPressed(KeyEvent.KEYCODE_2);
        } else if (v.getId() == R.id.Btn3) {
            keyPressed(KeyEvent.KEYCODE_3);
        } else if (v.getId() == R.id.Btn4) {
            keyPressed(KeyEvent.KEYCODE_4);
        } else if (v.getId() == R.id.Btn5) {
            keyPressed(KeyEvent.KEYCODE_5);
        } else if (v.getId() == R.id.Btn6) {
            keyPressed(KeyEvent.KEYCODE_6);
        } else if (v.getId() == R.id.Btn7) {
            keyPressed(KeyEvent.KEYCODE_7);
        } else if (v.getId() == R.id.Btn8) {
            keyPressed(KeyEvent.KEYCODE_8);
        } else if (v.getId() == R.id.Btn9) {
            keyPressed(KeyEvent.KEYCODE_9);
        } else if (v.getId() == R.id.Btn0) {
            keyPressed(KeyEvent.KEYCODE_0);
        } else if (v.getId() == R.id.BtnXing) {
            keyPressed(KeyEvent.KEYCODE_STAR);
        } else if (v.getId() == R.id.BtnJing) {
            keyPressed(KeyEvent.KEYCODE_POUND);
        }  else if (v.getId() == R.id.delete) {
            keyPressed(KeyEvent.KEYCODE_DEL);
        }  else if (v.getId() == R.id.contact_dial){
            showDialView();
        } else if (v.getId() == R.id.contact_history){
            gotoHistoryRecordActivity();
        }else if (v.getId() == R.id.contact_lianxi){
            gotoContactActivity(false);
        } else if (v.getId() == R.id.emerLy){
            gotoEmergencyContactActivity();
        }else if (v.getId() == R.id.dianhua_iv_contactActivity) {
            gotoContactActivity(true);
        }
    }

    private void gotoEmergencyContactActivity() {
        Intent intent = new Intent(getActivity(), EmergencyActivity.class);
        startActivity(intent);
    }


    private void showDialView() {
        if (dialView.getVisibility() == View.VISIBLE){
            contactView.setVisibility(View.VISIBLE);
            dialView.setVisibility(View.GONE);
        }else{
            contactView.setVisibility(View.GONE);
            dialView.setVisibility(View.VISIBLE);
        }

    }

    private void gotoHistoryRecordActivity() {
        if (getActivity() == null){
            return;
        }

        Intent intent = new Intent(getActivity(), HistoryActivity.class);
        getActivity().startActivity(intent);
    }

    private void gotoContactActivity(boolean canEdit) {
        if (getActivity() == null){
            return;
        }

        Intent intent = new Intent(getActivity(), ContactActivity.class);
        intent.putExtra(ContactActivity.CAN_EDIT, canEdit);
        getActivity().startActivity(intent);
    }

    private void keyPressed(int keyCode) {
        KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
        phoneNumberEdit.onKeyDown(keyCode, event);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String ss = s.toString();

        if (dialView.getVisibility() == View.VISIBLE){
            searchDial(ss);
        }else{
            searchContact(ss);
        }

    }

    private void searchContact(String name) {
        if (ObjUtil.isEmpty(contactPersons)){
            return;
        }

        if (TextUtils.isEmpty(name)){
            contactAdatper.setDatas(contactPersons);
        }

        List<Person> result = new ArrayList<Person>();
        for (Person person : contactPersons){
            if (person != null){
                String personName = person.getName();
                if (!TextUtils.isEmpty(personName) && personName.contains(name)){
                    result.add(person);
                }
            }
        }

        contactAdatper.setDatas(result);
    }

    List<Person> result = new ArrayList<>();
    private void searchDial(String phoneNumber) {
        if (ObjUtil.isEmpty(toDialPersons)){
            return;
        }

        if (TextUtils.isEmpty(phoneNumber)){
            dialAdatper.setData(toDialPersons);
            return;
        }

        result.clear();
        for (int i = 0; i < toDialPersons.size(); ++i){
            Person person = toDialPersons.get(i);

            if (person != null){
                if (person.getPhoneNumber() != null && person.getPhoneNumber().contains(phoneNumber)){
                    result.add(person);
                }
            }
        }

        dialAdatper.setData(result);
    }


}
